import {
	BaseElement,
	ChatStatus
} from "./base.js";


// 定义消息组件
class ChatMessagePanel extends BaseElement {
	constructor() {
		super();
		this.attachShadow({
			mode: 'open'
		});
		this.isLoadingHistory = false;
	}

	/**
	 * 面板
	 * @type {null}
	 */
	panel = null;

	connectedCallback() {
		this.render();
		this.setupScrollListener();
	}

	setupScrollListener() {
		this.panel.addEventListener('scroll', () => {
			if (this.panel.scrollTop === 0 && !this.isLoadingHistory) {
				// Get the first message's ID if exists
				console.log('id', this.panel.firstElementChild)
				const firstMsg = this.panel.firstElementChild;
				const lastId = firstMsg ? firstMsg.id : null;
				const oldScrollHeight = this.panel.scrollHeight;
				// Trigger history load

				console.log('id', lastId)
				this.chatInstance?.loadHistoryData(lastId).then(() => {
					const scrollDiff = this.panel.scrollHeight - oldScrollHeight;
					this.panel.scrollTop = scrollDiff;
				}).catch(() => {});

			}
		});
	}

	onReceive(key, value) {
		switch (key) {
			case "chatInstance":
				this.chatInstance.addChatMessageListener((msg) => {
					this.processMsg(msg);
				})
		}
	}

	processMsg(msg) {
		switch (msg.action) {
			case 'request':
				//发送消息
				this.addMessage(msg)
				if (msg.data.role == "user") {
					this.addMessage({
						...msg,
						data: {
							role: 'assistant',
							content: {
								text: ''
							}
						}
					})
				}

				break;
			case 'response':
			case 'reference': //添加引用
			case "error":
				let dom = this.findMessageDom(msg);
				if (dom && !dom.finish) {
					dom.render(msg);
				}
				//更新一条消息
				break;
			case 'over': {
				let dom = this.findMessageDom(msg);
				//结束对话
				if (dom != null && !dom.finish) {
					dom.notifyFinish();
				}
				break;
			}
			case 'insert':
				this.addHistoryMessage(msg);
				break;


			case 'syncData': {
				let dom = this.findMessageDom(msg);
				//结束对话
				if (dom != null) {
					dom.syncDbData(msg.data.response)
					dom.previousElementSibling.syncDbData(msg.data.request);
				}

				break;
			}


			case "regenerate": {
				const dom = this.findMessageDom(msg);
				//获取它的前一个元素
				const after = dom.nextElementSibling;
				dom.remove();
				this.addMessage({
					...msg,
					data: {
						role: 'assistant',
						content: {
							text: ''
						}
					}
				}, after)
			}



		}
	}


	findMessageDom(msg) {
		//更新一条消息
		let msgs = this.panel.childNodes;
		if (!msgs?.length) return;
		for (let i = msgs.length - 1; i >= 0; i--) {
			let m = msgs[i];
			if (m.flag == msg.flag && (!msg.data?.role || m.role == msg.data.role)) {
				//over状态没有data，所以，只需要判断flag即可
				return m;
			}
		}
		return null;
	}


	deleteMessage(flag) {
		let msgs = this.panel.childNodes;
		if (!msgs?.length) return;
		for (let i = msgs.length - 1; i >= 0; i--) {
			let m = msgs[i];
			if (m.flag == flag) {
				//over状态没有data，所以，只需要判断flag即可
				m.remove();
			}
		}
        if (!this.panel.childNodes?.length) {
            this.noMsgTip.classList.remove("hide")
        }
	}

	/**
	 * 添加一条消息
	 * @param msg
	 * @param next 插入到哪个元素之前
	 */
	addMessage(msg, next) {
		//动态构建一个 chatmessage组件并插入到container中
        this.noMsgTip.classList.add("hide")
		const el = document.createElement("chat-message");
		if (next) {
			this.panel.insertBefore(el, next);
			setTimeout(() => {
				el.scrollIntoView({
					behavior: 'smooth', // 平滑滚动
					block: 'start'     // 元素的顶部与视口的顶部对齐
				});
			},0)

		} else {
			this.panel.appendChild(el);
			// 平滑滚动到底部
			setTimeout(() => {
				this.scrollToBottom();
			},0)

		}
		//要先插入到页面，才能updateContent
		el.render(msg);


	}

	addHistoryMessage(msg) {
		const el = document.createElement("chat-message");
        this.noMsgTip.classList.add("hide")

		// Insert at the beginning for history messages
		if (this.panel.firstChild) {
			this.panel.insertBefore(el, this.panel.firstChild);
		} else {
			this.panel.appendChild(el);
		}

		el.render(msg);
		el.notifyFinish();
	}

	scrollToBottom() {
		// 获取所有消息元素
		const messages = this.panel.children;
		if (!messages.length) return;

		// 获取最后一条消息
		const lastMessage = messages[messages.length - 1];

		// 使用 scrollIntoView 平滑滚动
		lastMessage.scrollIntoView({
			behavior: 'smooth',
			block: 'end'
		});
	}

    clearAllMessages() {
        this.panel.innerHTML = "";
    }



	render() {
		this.shadowRoot.innerHTML = `
        <style>
            :host {
                flex: 1;
                overflow: hidden  !important;
                position: relative  !important;
                display: flex  !important;
                flex-direction: column  !important;
                position: relative;
            }
            .msg-panel {
                flex:1;
                overflow-y: auto;
                padding: 1rem;
            }
            .tip {
                position: absolute;
                width:100%;
                left:0;
                bottom: 0;
            }

            .msg-panel::-webkit-scrollbar {
                width: 4px !important; /* 滚动条宽度 */
            }

            .msg-panel::-webkit-scrollbar-track {
                background: rgba(241,241,241,0.7) !important; /* 滚动条轨道背景颜色 */
            }

            .msg-panel::-webkit-scrollbar-thumb {
                background: rgba(136,136,136,0.15) !important; /* 滚动条滑块颜色 */
                border-radius: 4px !important; /* 滚动条滑块圆角 */
            }
            .msg-panel::-webkit-scrollbar-thumb:hover {
                background: rgba(85,85,85,0.33) !important; /* 鼠标悬停时滚动条滑块颜色 */
            }
            .msg-panel::-webkit-scrollbar-button {
               display: none !important; /* 隐藏滚动条箭头 */
            }
            .nomsg_tip {
                display: flex;
                height: 100%;
                justify-content: center;
                align-items: center;
                font-size: 40px;
                color: #ceddf4;
            }
            .hide {
                display: none;
            }

        </style>
        <div class="msg-panel">
            <div id="panel"></div>
            <div class="nomsg_tip">
                <svg xmlns="http://www.w3.org/2000/svg" width="50" height="50" fill="#ceddf4" viewBox="0 0 512 512"><path d="M88 0C74.7 0 64 10.7 64 24c0 38.9 23.4 59.4 39.1 73.1l1.1 1C120.5 112.3 128 119.9 128 136c0 13.3 10.7 24 24 24s24-10.7 24-24c0-38.9-23.4-59.4-39.1-73.1l-1.1-1C119.5 47.7 112 40.1 112 24c0-13.3-10.7-24-24-24zM32 192c-17.7 0-32 14.3-32 32L0 416c0 53 43 96 96 96l192 0c53 0 96-43 96-96l16 0c61.9 0 112-50.1 112-112s-50.1-112-112-112l-48 0L32 192zm352 64l16 0c26.5 0 48 21.5 48 48s-21.5 48-48 48l-16 0 0-96zM224 24c0-13.3-10.7-24-24-24s-24 10.7-24 24c0 38.9 23.4 59.4 39.1 73.1l1.1 1C232.5 112.3 240 119.9 240 136c0 13.3 10.7 24 24 24s24-10.7 24-24c0-38.9-23.4-59.4-39.1-73.1l-1.1-1C231.5 47.7 224 40.1 224 24z"/></svg>
                <span style="margin-left: 4px;margin-top:10px">开始对话</span>
            </div>
        </div>
        <chat-tip class="tip"></chat-tip>
    `
		this.panel = this.shadowRoot.querySelector('#panel');
		this.noMsgTip = this.shadowRoot.querySelector('.nomsg_tip');
	}
}

export default ChatMessagePanel;